package com.zimi.core.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.zimi.bean.Constants;
import com.zimi.model.SysRole;
import com.zimi.model.SysRoleUser;
import com.zimi.model.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.zimi.core.security.AuthenticationFilter.isAppRequest;

/**
 * @author injury
 */
@Slf4j
@Component()
public class AuthenctiationSuccess extends SimpleUrlAuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        HttpSession session = request.getSession();

        Map<String, Object> result = new HashMap<>();
        if (isAppRequest) {
            result = (Map<String, Object>) session.getAttribute(Constants.APP_USER_INFO);
            String openId = (String) result.get("open_id");
            SysUser lUser = new SysUser().selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getOpenId, openId));
            if (lUser != null) {
                result.put("userId", lUser.getId());
                result.put("hasUser", true);
            } else result.put("hasUser", false);
        } else {
            String username = SecurityContextHolder.getContext()
                    .getAuthentication()
                    .getPrincipal()
                    .toString();
            SysUser loginUser = new SysUser().selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getLoginName, username));
            session.setAttribute(Constants.USER_SESSION_KEY, loginUser);

            // 保存超级管理员标志
            List<SysRoleUser> sysRoleUsers = new SysRoleUser().selectList(new LambdaQueryWrapper<SysRoleUser>().eq(SysRoleUser::getState, 1).eq(SysRoleUser::getUserId, loginUser.getId()));

            if (sysRoleUsers != null && sysRoleUsers.size() > 0) {
                List<Integer> ids = new ArrayList<>();

                for (SysRoleUser sru : sysRoleUsers) {
                    ids.add(sru.getRoleId());
                }

                List<SysRole> roles = new SysRole().selectList(new QueryWrapper<SysRole>().lambda().eq(SysRole::getRoleState, 1).in(SysRole::getId, ids).eq(SysRole::getFlag, 1));

                if (roles != null && roles.size() > 0) {
                    session.setAttribute(Constants.IS_ADMIN_FLAG, true);
                } else {
                    session.setAttribute(Constants.IS_ADMIN_FLAG, false);
                }
            } else {
                session.setAttribute(Constants.IS_ADMIN_FLAG, false);
            }
        }
        result.put("code", 200);
        result.put("msg", "登录成功");
        Gson gson = new Gson();
        response.setStatus(200);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(gson.toJson(result));
    }
}
